const puppeteer = require("puppeteer");
const fs = require('fs');

//生成PDF文件
const generatPDFFile = async (page, str) => {
  const path = `${Date.now()}.pdf`;
  if(str){
    console.log('--------- page set content --------');
    await page.setContent(str,{ waitUntil: 'networkidle0'});
  }
  await page.pdf({ path, format: "A4" });
};

(async () => {
  const browser = await puppeteer.launch({
    headless: true,
    args: ["--no-sandbox"],
  });
  const page = await browser.newPage();
  //通过HTML字符串生成
  const htmlStr = fs.readFileSync('./demo.html').toString();
  await generatPDFFile(page,htmlStr);
  //通过页面生成
  await page.goto("https://www.baidu.com");
  await generatPDFFile(page);
  
  await browser.close();
})();